package com.ten.mall.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ten.mall.service.CartService;
import com.ten.mall.service.ItemService;
import com.ten.mall.vo.Cart;
import com.ten.mall.vo.Item;
import com.ten.mall.vo.User;

@Controller
public class CartController {
	@Autowired
	private CartService cartService;
	@Autowired
	private ItemService itemService;
	/**
	 * 
	 * @param res
	 * @param start
	 * @return
	 */
	@RequestMapping("/phone/cart")
	public String tocart(HttpServletRequest res,
						 @RequestParam(name="start",defaultValue="1") Integer start){
		User u =(User) res.getSession().getAttribute("u");
		List<Cart> list =cartService.selectByPages(1, 20, u.getId());
		res.setAttribute("list", list);
		return "/phone/cart";
	}
	/**
	 * 添加购物车
	 * @param id
	 * @param test
	 * @param res
	 * @return
	 */
	@RequestMapping("/phone/addCart")
	@ResponseBody
	public String addCart(Integer id,Integer test,HttpServletRequest res){
		String result="error";
		try {
			User u =(User) res.getSession().getAttribute("u");
			Item item =itemService.selectById(id);
			Cart cart =new Cart();
			cart.setGoodsId(id);
			cart.setGoodsName(item.getGoodsName());
			cart.setGoodsPic(item.getGoodsPic());
			cart.setGoodsPrice(item.getGoodsPrice());
			cart.setGoodsNumber(test);
			cart.setGoodsTest(u.getId());
			cart.setGoodsStorage(item.getGoodsStorge());
			cartService.insertCart(cart);
			result="ok";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 删除购物车
	 * @param id
	 * @return
	 */
	@RequestMapping("/phone/delCart")
	@ResponseBody
	public String delCart(Integer id){
		String rs ="error";
		if(id!=null){
			try {
				cartService.deleteCart(id);
				rs="ok";
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return rs;
	}
}
